import { message } from "antd";
import axios, { AxiosResponse, InternalAxiosRequestConfig } from "axios";

axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
let baseURL = "http://localhost:8082/api/";

// axios.defaults.headers['clientid'] = import.meta.env.VITE_APP_CLIENT_ID;
// 创建 axios 实例
const service = axios.create({
  baseURL,
  timeout: 50000,
});

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    config.headers["authorization"] = `Bearer sadfasdf`;
    return config;
  },
  (error: any) => {
    console.log(error);
    return Promise.reject(error);
  }
);
const codeMap: any = {};

// 响应拦截器
service.interceptors.response.use(
  (res: AxiosResponse, ...args) => {
    const code = res.data.code;
    const msg = codeMap[code] || res.data.msg;
    // 二进制数据则直接返回
    if (
      res.request.responseType === "blob" ||
      res.request.responseType === "arraybuffer"
    ) {
      return res.data;
    }
    if (!(code == 200 || code == 0)) {
      message.error(msg || "请求失败");
      throw res.data;
    } else {
      return res.data?.data;
    }
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

// 导出 axios 实例
export default service;
